package handle

import (
	"encoding/json"
	"fmt"

	utilx "protocx/entity"
	"protocx/protobufx"

	"github.com/emicklei/go-restful/v3"
)

type Resp struct {
}

func (r Resp) InitRoute(container *restful.Container) {
	ws := new(restful.WebService)
	ws.Route(ws.GET("/resp/string").To(r.String()))
	ws.Route(ws.GET("/resp/json").To(r.Json()))
	ws.Route(ws.GET("/resp/jsonp").To(r.JSONP()))
	ws.Route(ws.GET("/resp/xml").To(r.XML()))
	ws.Route(ws.GET("/resp/file").To(r.FILE()))
	ws.Route(ws.GET("/resp/blob").To(r.Blob()))
	for _, route := range ws.Routes() {
		fmt.Println(route.Method, route.Path)
	}
	container.Add(ws)

}
func (r Resp) String() restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		response.Write([]byte("string"))
	}
}
func (r Resp) Json() restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		fmt.Println("json")
		response.WriteAsJson(utilx.Resp{
			Code: 200,
			Msg:  "",
			Data: nil,
		})
	}
}
func (r Resp) JSONP() restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		response.WriteEntity(&protobufx.LoginRequest{
			Code: 879,
		})
	}
}
func (r Resp) JSONPretty() restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		response.PrettyPrint(true)
		response.WriteEntity(&protobufx.LoginRequest{
			Code: 879,
		})
	}
}
func (r Resp) XML() restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		response.WriteAsXml(utilx.Resp{
			Code: 200,
			Msg:  "",
			Data: nil,
		})
	}
}
func (r Resp) FILE() restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		bytes := []byte("file")
		response.Write(bytes)
	}
}
func (r Resp) Blob() restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		marshal, _ := json.Marshal(utilx.Resp{
			Code: 12,
			Msg:  "msg",
			Data: nil,
		})
		response.Write(marshal)
	}
}
